package com.songqi.common.log.service;

import com.songqi.common.core.constant.Constants;
import com.songqi.common.core.utils.ServletUtils;
import com.songqi.common.core.utils.ip.IpUtils;
import com.songqi.common.log.domain.LoginInfoLog;
import com.songqi.common.log.domain.OperationInfoLog;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.TimerTask;

/**
 * 异步工厂（产生任务用）
 *
 * @author songqi(13776346982)
 */
public class AsyncLog {
    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    @Resource
    private LogApi logApi;

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status 状态
     * @param message 消息
     * @param args 列表
     * @return 任务task
     */
    public TimerTask recordLoginInfo(final String username, final String status, final String message,
                                     final Object... args)
    {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        return new TimerTask()
        {
            @Override
            public void run()
            {
                String address = IpUtils.getLocationByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(getBlock(ip));
                s.append(address);
                s.append(getBlock(username));
                s.append(getBlock(status));
                s.append(getBlock(message));
                // 打印信息到日志
                sys_user_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                LoginInfoLog loginInfoLog = new LoginInfoLog();
                loginInfoLog.setUserName(username);
                loginInfoLog.setIpaddr(ip);
                loginInfoLog.setLoginLocation(address);
                loginInfoLog.setBrowser(browser);
                loginInfoLog.setOs(os);
                loginInfoLog.setMsg(message);
                // 日志状态
                if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status))
                {
                    loginInfoLog.setStatus(Constants.SUCCESS);
                }
                else if (Constants.LOGIN_FAIL.equals(status))
                {
                    loginInfoLog.setStatus(Constants.FAIL);
                }

                logApi.saveLoginLog(loginInfoLog);
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @param operLog 操作日志信息
     * @return 任务task
     */
    public TimerTask recordOperateLog(final OperationInfoLog operLog)
    {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                // 远程查询操作地点
                operLog.setOptLocation(IpUtils.getLocationByIP(operLog.getOptIp()));
                logApi.saveOperationLog(operLog);
            }
        };
    }


    private static String getBlock(Object msg)
    {
        if (msg == null)
        {
            msg = "";
        }
        return "[" + msg.toString() + "]";
    }




}
